package com.hertz.iris.view.alert;

import javax.inject.Inject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.hertz.iris.Injector;
import com.hertz.iris.core.MatchAlarmService;
import com.hertz.iris.core.TriggerService;
import com.hertz.iris.dao.MatchAlarmDao;
import com.hertz.iris.pojo.MatchAlarm;
import com.hertz.iris.pojo.MatchNba;
import com.hertz.iris.pojo.ResponseIsAlert;
import com.hertz.iris.util.Constants;
import com.hertz.iris.util.Ln;
import com.hertz.iris.util.SafeAsyncTask;

public class MatchAlarmRec extends BroadcastReceiver {
	@Inject MatchAlarmService matchAlarmService;
	@Inject TriggerService triggerService;
	@Override
	public void onReceive(Context context, Intent intent) {
//		AlarmAlertWakeLock.acquire(context);
		Injector.inject(this);
		new Alert(context, intent).execute();
//		triggerService.matchAlarmAlertTrigger(System.currentTimeMillis() + Constants.DEFAULT_INTERVAL);
	}
	
	private class Alert extends SafeAsyncTask<ResponseIsAlert> {

        private final Context context;
        private final Intent intent;
        private MatchAlarm localMa;

        protected Alert(Context context,Intent intent) {
            this.context = context;
            this.intent = intent;
            localMa = (MatchAlarm)intent.getSerializableExtra(MatchAlarmDao.TABLENAME);
        }

        @Override
        public ResponseIsAlert call() throws Exception {
        	if(localMa == null)
        		return null;
        	ResponseIsAlert result = matchAlarmService.getAlert(context,localMa.getMid());
        	return result;
        }

        @Override
        protected void onSuccess(ResponseIsAlert var) throws Exception {
        	Ln.d("Logout succeeded: %s", var);
        	if(var == null){
        		return;
        	}
        	MatchNba matchNba = var.getMatchNba();
        	if(var.getAlert()){
        		matchAlarmService.createNotication(var, context);
        	}
        	
        	if(var.getAfter() > 0){
        		matchAlarmService.createMatchAlarmTrigger(localMa, System.currentTimeMillis() + var.getAfter());
        	}
        	
        	localMa.setStatus(var.getIrisNbaAlarm().getStatus());
        	matchAlarmService.SaveOrUpdateToLocal(localMa);
        }

        @Override
        protected void onException(Exception e) throws RuntimeException {
            super.onException(e);
            Ln.e(e.getCause(), "Logout failed.");
            matchAlarmService.createMatchAlarmTrigger(localMa, System.currentTimeMillis() + Constants.DEFAULT_INTERVAL);
        }
    }

}
